#include "delay.h"


static uint8_t  systime_us = 0;							
static uint16_t systime_ms = 0;							


void SystickConfig()
{	
	SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk;	
	
	systime_us = SystemCoreClock / 1000000;				

	systime_ms = (uint16_t)systime_us * 1000;					

}								    
	    								   
void DelayUs(uint32_t num_us)
{		
	uint32_t temp;	    	 
	SysTick->LOAD = (num_us*systime_us-1); 					
	SysTick->VAL = 0x00;        					
	SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk ;	
	do
	{
		temp = SysTick->CTRL;
	}while((temp & 0x01) && !(temp & (1 << 16)));		
	SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;	
	SysTick->VAL = 0X00;      					
}

void DelayMs(uint16_t num_ms)
{	 		  	  
	uint32_t temp,i,Rem,Quo;	

	Quo = num_ms/200;
	Rem = num_ms%200;
	
	if(Quo > 0)
	{
		for(i = 0; i < Quo;i++)
		{
			IWDT->CLR = 0xAAAA;
			SysTick->LOAD = (uint32_t)(200*systime_ms-1);				
			SysTick->VAL = 0x00;							
			SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk ;	
			do
			{
				temp = SysTick->CTRL;
			}while((temp & 0x01) && !(temp & (1 << 16)));		
			SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;	
			SysTick->VAL = 0X00;
		}
	}
	
	if(Rem > 0)
	{
		IWDT->CLR = 0xAAAA;
		SysTick->LOAD = (uint32_t)(Rem*systime_ms-1);				
		SysTick->VAL = 0x00;							
		SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk ;	
		do
		{
			temp = SysTick->CTRL;
		}while((temp & 0x01) && !(temp & (1 << 16)));		
		SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;	
		SysTick->VAL = 0X00; 
	}  					
} 


